home *** CD-ROM | disk | FTP | other *** search
Text File | 1997-06-28 | 2.7 KB | 177 lines | [TEXT/CWIE] |
- // TreeNode.cp
-
- #ifndef TreeNode_h
- #include "TreeNode.h"
- #endif
- #ifndef Tree_h
- #include "Tree.h"
- #endif
- #ifndef Swap_h
- #include "Swap.h"
- #endif
- #ifndef MinMax_h
- #include "MinMax.h"
- #endif
-
- TreeNode::TreeNode()
- : tree( 0 ),
- parent( 0 ),
- left( 0 ),
- right( 0 )
- {
- }
-
- TreeNode::~TreeNode()
- {
- Assert( left == 0 );
- Assert( right == 0 );
-
- if ( tree != 0 )
- tree->Remove( *this );
-
- Assert( tree == 0 );
- Assert( parent == 0 );
- }
-
- TreeNode *TreeNode::NextNode() const
- {
- if ( right != 0 )
- {
- TreeNode *n( right );
- while ( n->left != 0 )
- n = n->left;
- return n;
- }
-
- const TreeNode *n( this );
- while ( n->IsRightChild() )
- n = n->parent;
-
- return n->parent;
- }
-
- TreeNode* TreeNode::PreviousNode() const
- {
- if ( left != 0 )
- {
- TreeNode *n( left );
- while ( n->right != 0 )
- n = n->right;
- return n;
- }
-
- const TreeNode *n( this );
- while ( n->IsLeftChild() )
- n = n->parent;
-
- return n->parent;
- }
-
- TreeNode* TreeNode::SiblingNode() const
- {
- if ( IsRoot() )
- return 0;
-
- if ( IsLeftChild() )
- return parent->right;
-
- Assert( IsRightChild() );
- return parent->left;
- }
-
- TreeNode*& TreeNode::LinkFromAbove()
- {
- Assert( Owned() );
-
- if ( IsRoot() )
- return tree->root;
-
- if ( IsLeftChild() )
- return parent->left;
-
- Assert( IsRightChild() )
- return parent->right;
- }
-
- void TreeNode::SwapWith( TreeNode& n )
- {
- if ( Owned() )
- LinkFromAbove() = &n;
-
- if ( n.Owned() )
- n.LinkFromAbove() = this;
-
- Swap( tree, n.tree );
- Swap( parent, n.parent );
- Swap( left, n.left );
- Swap( right, n.right );
-
- if ( left != 0 )
- left->parent = this;
- if ( right != 0 )
- right->parent = this;
-
- if ( n.left != 0 )
- n.left->parent = &n;
- if ( n.right != 0 )
- n.right->parent = &n;
-
- }
-
- void TreeNode::RotateUp()
- {
- Assert( Owned() );
- Assert( !IsRoot() );
-
- TreeNode& falling( *parent );
-
- falling.LinkFromAbove() = this;
- parent = falling.parent;
- falling.parent = this;
-
- if ( falling.left == this )
- {
- if ( right != 0 )
- right->parent = &falling;
- falling.left = right;
- right = &falling;
- }
- else
- {
- Assert( falling.right == this );
- if ( left != 0 )
- left->parent = &falling;
- falling.right = left;
- left = &falling;
- }
- }
-
- uint32 TreeNode::Depth() const
- {
- uint32 depth = 0;
- for ( const TreeNode *n = parent; n != 0; n = n->parent )
- depth++;
-
- return depth;
- }
-
- bool TreeNode::Valid() const
- {
- if ( !Owned() )
- return parent == 0 && left == 0 && right == 0;
-
- if ( left != 0 && left->parent != this )
- return false;
-
- if ( right != 0 && right->parent != this )
- return false;
-
- if ( left != 0 && left == right )
- return false;
-
- if ( IsRoot() )
- return tree->root == this;
-
- return IsLeftChild() || IsRightChild();
- }
-